from aws_cdk import (
    aws_autoscaling as autoscaling,
    aws_ec2 as ec2,
    aws_ecs as ecs,
    aws_iam as iam,
    App, Stack
)
from constructs import Construct
from aws_cdk import aws_elasticloadbalancingv2 as elbv2  # 新增导入
from aws_cdk import CfnOutput

class ECSCluster(Stack):

    def __init__(self, scope: Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, *kwargs)

        vpc = ec2.Vpc(
            self, "MyVpc",
            max_azs=2
        )
        # 添加 ECS 实例角色
        ecs_role = iam.Role(
            self, "EcsInstanceRole",
            assumed_by=iam.ServicePrincipal("ec2.amazonaws.com"),
            managed_policies=[
                iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AmazonEC2ContainerServiceforEC2Role")
            ]
        )
        # 替换 AutoScalingGroup 的启动配置为启动模板
        launch_template = ec2.LaunchTemplate(
            self, "LaunchTemplate",
            instance_type=ec2.InstanceType("t2.xlarge"),
            machine_image=ecs.EcsOptimizedImage.amazon_linux2(),
            security_group=ec2.SecurityGroup(self, "SG", vpc=vpc),
            associate_public_ip_address=True,
            user_data=ec2.UserData.for_linux(),
            role = ecs_role
        )

        asg = autoscaling.AutoScalingGroup(
            self, "MyFleet",
            launch_template=launch_template,
            desired_capacity=3,
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
        )

        cluster = ecs.Cluster(
            self, 'EcsCluster',
            vpc=vpc
        )

        capacity_provider = ecs.AsgCapacityProvider(self, "AsgCapacityProvider",
            auto_scaling_group=asg
        )
        cluster.add_asg_capacity_provider(capacity_provider)

        # 添加测试任务
        task_definition = ecs.Ec2TaskDefinition(
            self, "TestTask",
            network_mode=ecs.NetworkMode.AWS_VPC
        )
        task_definition.add_container(
            "TestContainer",
            image=ecs.ContainerImage.from_registry("nginx:alpine"),  # 使用Nginx测试镜像
            memory_limit_mib=256,
            cpu=256,
            port_mappings=[ecs.PortMapping(container_port=80)]
        )

        service = ecs.Ec2Service(
            self, "TestService",
            cluster=cluster,
            task_definition=task_definition,
            desired_count=1,
        )
         # 创建负载均衡器
        lb = elbv2.ApplicationLoadBalancer(
            self, "ServiceLB",
            vpc=vpc,
            internet_facing=True
        )
        # 添加监听器
        listener = lb.add_listener("Listener", port=80)
        listener.add_targets(
            "ECSTarget",
            port=80,
            targets=[service]
        )

        # 输出 URL
        CfnOutput(
            self, "ServiceEndpoint",
            value=f"http://{lb.load_balancer_dns_name}",
            description="Nginx Service URL"
        )


app = App()
ECSCluster(app, "MyFirstEcsCluster")
app.synth()
